package pers.llc.css.lock.unreentrant;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 通过自旋锁模拟一个不可重入锁
 *
 * @author lls
 * @time 2019/4/7 0007 15:34
 */
public class UnreentrantLock {

    private AtomicReference<Thread> owner = new AtomicReference<>();

    public void lock() {
        Thread current = Thread.currentThread();
        for (; ; ) {
            if (!owner.compareAndSet(null, current)) {
                return;
            }
        }
    }

    public void unlock() {
        Thread current = Thread.currentThread();
        owner.compareAndSet(current, null);
    }

}
